---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[

]]--
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 参数
    local MAX_COOL_DOWN_TIME = TUNING.LORAMIA_DEBUGGING_MODE and 60 or 3*8*60
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 素材
    local assets =
    {
        Asset("ANIM", "anim/loramia_item_mechanical_dog_hat.zip"),
    }
    local Widget = require "widgets/widget"
    local Image = require "widgets/image" -- 引入image控件
    local UIAnim = require "widgets/uianim"
    local Screen = require "widgets/screen"
    local AnimButton = require "widgets/animbutton"
    local ImageButton = require "widgets/imagebutton"
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 穿戴
    local function onequip(inst, owner)
        ------------------------------------------------------------------------------------------------------------------------------
        --- 激活功能
            if owner and owner:HasTag("player") and owner.userid then
                inst.components.loramia_com_inspectacle_searcher:Active(owner)
            end
        ------------------------------------------------------------------------------------------------------------------------------
        --- 动画
            owner.AnimState:OverrideSymbol("swap_hat", "loramia_item_mechanical_dog_hat", "swap_hat")
            owner.AnimState:Show("HAT")
            owner.AnimState:Show("HAIR_HAT")
            owner.AnimState:Hide("HAIR_NOHAT")
            owner.AnimState:Hide("HAIR")
            if owner:HasTag("player") then
                owner.AnimState:Hide("HEAD")
                owner.AnimState:Show("HEAD_HAT")
                owner.AnimState:Show("HEAD_HAT_NOHELM")
                owner.AnimState:Hide("HEAD_HAT_HELM")
            end
        ------------------------------------------------------------------------------------------------------------------------------
    end
    local function onunequip(inst, owner)
        ------------------------------------------------------------------------------------------------------------------------------
        --- 解除功能
            inst.components.loramia_com_inspectacle_searcher:Deactive()
        ------------------------------------------------------------------------------------------------------------------------------
        --- 动画
            owner.AnimState:ClearOverrideSymbol("swap_hat")
            owner.AnimState:Hide("HAT")
            owner.AnimState:Hide("HAIR_HAT")
            owner.AnimState:Show("HAIR_NOHAT")
            owner.AnimState:Show("HAIR")
            if owner:HasTag("player") then
                owner.AnimState:Show("HEAD")
                owner.AnimState:Hide("HEAD_HAT")
                owner.AnimState:Hide("HEAD_HAT_NOHELM")
                owner.AnimState:Hide("HEAD_HAT_HELM")
            end
        ------------------------------------------------------------------------------------------------------------------------------
    end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- wiget
    local function hud_install(inst,root)
        ---------------------------------------------------------------
        --- 按钮
            local deep_search_btn = root:AddChild(ImageButton("images/widgets/loramia_spell_ring.xml","empty.tex","empty.tex","empty.tex","empty.tex","empty.tex"))
            -- deep_search_btn:SetScale(.5,.5)
            -- deep_search_btn:SetPosition(500,-200)
            deep_search_btn:SetScale(.7,.7)
            deep_search_btn:SetPosition(200,200)
            deep_search_btn.inst:ListenForEvent("close",function()
                deep_search_btn:Hide()
            end,root.inst)
            deep_search_btn:SetOnClick(function()
                -- print("666666666 click")
                ThePlayer.replica.loramia_com_rpc_event:PushEvent("create_marker",{},inst)
                deep_search_btn:Hide()
            end)
            deep_search_btn:Hide()
        ---------------------------------------------------------------
        --- 图标
            local icon = deep_search_btn.image:AddChild(UIAnim())
            icon:GetAnimState():SetBuild("loramia_item_mechanical_dog_hat")
            icon:GetAnimState():SetBank("loramia_item_mechanical_dog_hat")
            icon:GetAnimState():PlayAnimation("icon",true)
            local icon_scale = 0.3
            icon:SetScale(icon_scale,icon_scale)
            icon:SetPosition(0,-10)
        ---------------------------------------------------------------
        --- 
            root.inst:DoPeriodicTask(1,function()
                if inst.replica.loramia_com_inspectacle_searcher:GetPingerTarget() == nil and inst:HasTag("ready") then
                    inst.replica.loramia_com_inspectacle_searcher:SetPingerTarget(TheSim:FindFirstEntityWithTag("loramia_building_inspectaclesbox"))
                end
                if inst.replica.loramia_com_inspectacle_searcher:GetPingerTarget() == nil 
                    and inst.replica.loramia_com_inspectacle_searcher:GetPingerTargetPos() == nil
                    and inst:HasTag("ready") then
                    deep_search_btn:Show()
                else
                    deep_search_btn:Hide()
                end
            end)
        ---------------------------------------------------------------
        --- 
            root.inst:ListenForEvent("pinger_pos_set",function(_,pos)
                inst.replica.loramia_com_inspectacle_searcher:SetPingerTargetPos(pos)
            end,inst)
        ---------------------------------------------------------------
        --- 激活视野，看见目标
            if ThePlayer then
                ThePlayer.AnimState:SetClientSideBuildOverrideFlag("loramia_building_inspectaclesbox_searching", true)
            end
            root.inst:ListenForEvent("close",function()
                if ThePlayer then
                    ThePlayer.AnimState:SetClientSideBuildOverrideFlag("loramia_building_inspectaclesbox_searching", false)
                end
            end)
        ---------------------------------------------------------------
    end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- 随机坐标（复制自 传送法杖）
    local function GetRandomPosition_staff(caster, teleportee, target_in_ocean)
        if teleportee == nil then
            teleportee = caster
        end

        if target_in_ocean then
            local pt = TheWorld.Map:FindRandomPointInOcean(20)
            if pt ~= nil then
                return pt
            end
            local from_pt = teleportee:GetPosition()
            local offset = FindSwimmableOffset(from_pt, math.random() * 2 * PI, 90, 16)
                            or FindSwimmableOffset(from_pt, math.random() * 2 * PI, 60, 16)
                            or FindSwimmableOffset(from_pt, math.random() * 2 * PI, 30, 16)
                            or FindSwimmableOffset(from_pt, math.random() * 2 * PI, 15, 16)
            if offset ~= nil then
                return from_pt + offset
            end
            return teleportee:GetPosition()
        else
            local centers = {}
            for i, node in ipairs(TheWorld.topology.nodes) do
                if TheWorld.Map:IsPassableAtPoint(node.x, 0, node.y) and node.type ~= NODE_TYPE.SeparatedRoom then
                    table.insert(centers, {x = node.x, z = node.y})
                end
            end
            if #centers > 0 then
                local pos = centers[math.random(#centers)]
                return Vector3(pos.x, 0, pos.z)
            else
                return caster:GetPosition()
            end
        end
    end
    local function GetRandomPosition(player) --- 锁定范围内寻找。
        local min_radius = 50
        local max_radius = 80
        local min_radius_sq = min_radius * min_radius
        local max_radius_sq = max_radius * max_radius

        local pt = nil
        local test_num = 1000
        while test_num > 0 do
            pt = GetRandomPosition_staff(player)
            local temp_dis_sq = player:GetDistanceSqToPoint(pt.x,0,pt.z)
            if temp_dis_sq >= min_radius_sq and temp_dis_sq <= max_radius_sq then
                break
            end
            test_num = test_num - 1
        end
        return pt
    end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 创建标记
    local function CreateMarker(inst)
        print("CreateMarker")
        local marker = TheSim:FindFirstEntityWithTag("loramia_building_inspectaclesbox")
        if marker and marker:IsValid() then
            -- print("marker is valid")
            -- inst.components.loramia_com_inspectacle_searcher:SetPingerTarget(marker)
            return
        end
        if not inst.components.rechargeable:IsCharged() then
            -- print("not charged")
            return
        end
        local player = inst.components.loramia_com_inspectacle_searcher:GetOwner() or TheSim:FindFirstEntityWithTag("player")
        if player == nil then
            -- print("player is nil")
            return
        end
        local pos = GetRandomPosition(player)
        SpawnPrefab("loramia_building_inspectaclesbox").Transform:SetPosition(pos.x,0,pos.z)
        inst.components.rechargeable:Discharge(MAX_COOL_DOWN_TIME)
    end
    --- 服务器定期扫描下发坐标给客户端，通过RPC。用来解决 目标物品 在加载范围外无法在客户端扫描到的bug
    local function Marker_Searching_Task(inst)
        local marker = TheSim:FindFirstEntityWithTag("loramia_building_inspectaclesbox")
        local owner = inst.components.loramia_com_inspectacle_searcher:GetOwner()
        if owner == nil then
            return
        end
        if marker and marker:IsValid() then
            owner.components.loramia_com_rpc_event:PushEvent("pinger_pos_set",Vector3(marker.Transform:GetWorldPosition()),inst)
        else
            owner.components.loramia_com_rpc_event:PushEvent("pinger_pos_set",nil,inst)
        end
    end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- ready checker
    local function ready_checker(inst)
        if inst.components.rechargeable:IsCharged() then
            inst:AddTag("ready")
        else
            inst:RemoveTag("ready")
        end
    end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 转换事件
    local function item_trans_event_install(inst)
        inst:ListenForEvent("unequipped",function()
            local x,y,z = inst.Transform:GetWorldPosition()
            local owner = inst.components.inventoryitem.owner
            if owner and owner.components.inventory then
                owner.components.inventory:SetActiveItem(inst)
            end
            inst:Remove()
            SpawnPrefab("loramia_item_mechanical_dog").Transform:SetPosition(x,y,z)
        end)
    end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- 物品
    local function fn()
        local inst = CreateEntity()

        inst.entity:AddTransform()
        inst.entity:AddAnimState()
        inst.entity:AddSoundEmitter()
        inst.entity:AddNetwork()

        MakeInventoryPhysics(inst)

        inst.AnimState:SetBank("loramia_item_mechanical_dog_hat")
        inst.AnimState:SetBuild("loramia_item_mechanical_dog_hat")
        inst.AnimState:PlayAnimation("item")
        inst:AddTag("loramia_item_mechanical_dog_hat")
        inst:AddTag("nightvision") --- 鼹鼠帽 夜视效果
        inst.entity:SetPristine()
        ---------------------------------------------------------------------
        ---
            inst:ListenForEvent("hud_created",hud_install)
        ---------------------------------------------------------------------

        if not TheWorld.ismastersim then
            return inst
        end
        ---------------------------------------------------------------------
        --- 
            item_trans_event_install(inst)
            inst:ListenForEvent("create_marker",CreateMarker)
            inst:DoPeriodicTask(5,Marker_Searching_Task)
        ---------------------------------------------------------------------
        --- 基础组件
            inst:AddComponent("inspectable")
            inst:AddComponent("inventoryitem")
            -- inst.components.inventoryitem:ChangeImageName("bluegem")
            inst.components.inventoryitem.imagename = "loramia_item_mechanical_dog_hat"
            inst.components.inventoryitem.atlasname = "images/map_icons/loramia_item_mechanical_dog_hat.xml"
            inst.components.inventoryitem:SetSinks(true)
            inst:AddComponent("equippable")
            inst.components.equippable:SetOnEquip(onequip)
            inst.components.equippable:SetOnUnequip(onunequip)
            inst.components.equippable.equipslot = EQUIPSLOTS.HEAD

            MakeHauntableLaunch(inst)
        ---------------------------------------------------------------------
        --- 核心寻宝组件
            inst:AddComponent("loramia_com_inspectacle_searcher")
        ---------------------------------------------------------------------
        --- 冷却
            inst:AddComponent("rechargeable")
            inst.components.rechargeable:SetMaxCharge(MAX_COOL_DOWN_TIME)
            inst:DoPeriodicTask(1,ready_checker)
        ---------------------------------------------------------------------
        return inst
    end
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return Prefab("loramia_item_mechanical_dog_hat", fn, assets)
